package org.lex.ftp.util.bookmark;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;

import javax.swing.JMenu;
import javax.swing.JMenuItem;

import org.lex.ftp.FTP;
import org.lex.ftp.ui.actions.OpenSiteAction;
import org.lex.ftp.util.prefs.Prefs;


public class BookmarkUtils {
	public static void main(String[] args) {
	}

	public static Bookmark loadBookmark() throws Exception {
		throw new UnsupportedOperationException();
	}

	public static void storeBookmark(Bookmark bm) throws IOException, Exception {
		storeBookmark(bm, new OutputStreamWriter(new FileOutputStream(Prefs.getBookmarkFile()), Charset.defaultCharset()));
	}

	public static void storeBookmark(Bookmark bm, Writer out) {
		throw new UnsupportedOperationException();
	}

	public static JMenuItem[] getBookmarkMenu(FTP app) {
		Bookmark root;
		try {
			root = loadBookmark();
		} catch (Exception e) {
			e.printStackTrace();
			return new JMenuItem[0];
		}
		JMenuItem[] menus = new JMenuItem[root.getFolderCount() + root.getSiteCount()];
		for (int i = 0, n = root.getFolderCount(); i < n; i++)
			menus[i] = createBookmarkMenu(app, root.getFolder(i));
		int fc = root.getFolderCount();
		for (int i = 0, n = root.getSiteCount(); i < n; i++)
			menus[fc + i] = new JMenuItem(new OpenSiteAction(app, root.getSite(i)));
		return menus;
	}

	private static JMenu createBookmarkMenu(FTP app, Bookmark bookmark) {
		JMenu menu = new JMenu(bookmark.getName());
		for (int i = 0, n = bookmark.getFolderCount(); i < n; i++)
			menu.add(createBookmarkMenu(app, bookmark.getFolder(i)));
		for (int i = 0, n = bookmark.getSiteCount(); i < n; i++)
			menu.add(new OpenSiteAction(app, bookmark.getSite(i)));
		return menu;
	}
}
